package libaray;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreInputStream;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.files.FinalizationException;
import com.google.appengine.api.files.LockException;

public class File {
	public static String Create(String str) {
		FileService fileService = FileServiceFactory.getFileService();

		// Create a new Blob file with mime-type "text/plain"
		AppEngineFile file = null;
		try {
			file = fileService.createNewBlobFile("text/html");
		} catch (IOException e) {
			e.printStackTrace();
		}

		// Open a channel to write to it
		boolean lock = true;
		FileWriteChannel writeChannel = null;
		try {
			writeChannel = fileService.openWriteChannel(file, lock);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (FinalizationException e) {
			e.printStackTrace();
		} catch (LockException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// Different standard Java ways of writing to the channel
		// are possible. Here we use a PrintWriter:
		PrintWriter out = new PrintWriter(Channels.newWriter(writeChannel,
				"UTF8"));
		out.println(str);

		// Close without finalizing and save the file path for writing later
		out.flush();
		out.close();

		try {
			writeChannel.closeFinally();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return fileService.getBlobKey(file).getKeyString();
	}

	public static String Read(String path) throws FileNotFoundException {

		String str = "";

		InputStream blobStream = null;
		try {
			blobStream = new BlobstoreInputStream(new BlobKey(path));
		}

		catch (IOException es) {
			blobStream = new FileInputStream("WEB-INF/appengine-generated/" + path);
		}
		// Again, different standard Java ways of reading from the channel.
		BufferedReader reader = new BufferedReader(new InputStreamReader(blobStream));
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				str += line;

			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return str;
	}
}
